package com.sitechasia.webx.components.xtable.view.pms;

import org.extremecomponents.table.bean.Table;
import org.extremecomponents.table.core.TableModel;
import org.extremecomponents.table.view.html.BuilderUtils;
import org.extremecomponents.table.view.html.TableActions;
import org.extremecomponents.table.view.html.toolbar.ImageItem;
import org.extremecomponents.table.view.html.toolbar.ToolbarItemUtils;
import org.extremecomponents.util.HtmlBuilder;
/**
 * 功能描述：根据UI设计，负责创建toolbarTable
 * UI设计中，把表头，body,foot用三个表格一起放的，在这里模拟UI实现
 * <p>版权所有：中企动力
 * <p>未经本公司许可，不得以任何方式复制或使用本程序任何部分
 * @author 易贤建
 * Created on 2008-4-28
 */
public class CeToolbarBuilder {
	private HtmlBuilder htmlBuilder;
	private TableModel model;
	private final String totalMessage = "toolbar.text.totalMessage";
	private final int allPages = 5;

	public CeToolbarBuilder(HtmlBuilder builder, TableModel model){
		this.htmlBuilder = builder;
		this.model = model;
	}
	/**
     * Function:根据UI，生成分页的toolbar框架开始部分
     * Create author:易贤建
     * Create on:2008-4-15
	 */
	public CeToolbarBuilder toolbarTableStart(){
		htmlBuilder.table(1).width("100%").cellPadding("0").cellSpacing("0").styleClass("bg_listPageNum").close().newline();
		htmlBuilder.tab().append("<tfoot>");
		htmlBuilder.tr(2).close();
		return this;
	}

	public void toolbarTableEnd(){
		getHtmlBuilder().append("</tfoot>").tableEnd(0);
	}
	/**
     * Function:显示总行数的记录:共**个记录
     * Create author:易贤建
     * Create on:2008-4-15
	 */
	public CeToolbarBuilder buildTotalCountMessage(){
		Boolean isShowTotalMessage = Boolean.valueOf(model.getTableHandler().getTable().getAttributeAsString("isShowTotalMessage"));
		if(!isShowTotalMessage) return this;  //如果要求不显示 则直接过滤
		htmlBuilder.td(3).close();
		String strTotal = model.getMessages().getMessage(totalMessage,new String[]{builderTotalMessage()});
		htmlBuilder.append(strTotal);
		htmlBuilder.tdEnd();
		return this;
	}

	/**
     * Function:创建分页相关的：如首页，上一页，下一页，末页等
     * Create author:易贤建
     * Create on:2008-4-15
	 */
	public CeToolbarBuilder buildPagination(){
		htmlBuilder.td(3).styleClass("align_right").close().newline();
		getHtmlBuilder().tabs(3);
		firstPageItemAsImage();  //首页
		getHtmlBuilder().nbsp().newline();
		getHtmlBuilder().tabs(3);
		prevPageItemAsImage();  //上一页
		getHtmlBuilder().nbsp().newline();
		//页面跳转
		forwardToPageWithPageNumber();  //超链接
		getHtmlBuilder().tabs(3);
		nextPageItemAsImage();  //下一页
		getHtmlBuilder().nbsp().newline();
		getHtmlBuilder().tabs(3);
		lastPageItemAsImage();  //最后一页
		getHtmlBuilder().nbsp().newline();
		buildTotalPageMessage();
		return this;
	}

	/**
     * Function:获取配置文件中的总行数的配置，并注入参数--实际的总行数
     * Create author:易贤建
     * Create on:2008-4-15
	 */
	protected String builderTotalMessage(){
		Integer totalRows = model.getLimit().getTotalRows();
		StringBuffer strArgs = new StringBuffer("<span class=\"fontredblod\">");
		strArgs.append(totalRows);
		strArgs.append("</span>");
		return strArgs.toString();
	}
	/**
     * Function:显示第一页图片
     * Create author:易贤建
     * Create on:2008-4-15
	 */
	protected void firstPageItemAsImage(){
		//创建基本信息
		ImageItem imageItem = new ImageItem();
		imageItem.setImage(getImagePath("arrowpageleftend"));
		imageItem.setDisabledImage(getImagePath("arrowpageleftend"));
		imageItem.setAlt(model.getMessages().getMessage("toolbar.tooltip.firstPage"));
		imageItem.setStyle("border:0");
		ToolbarItemUtils.buildFirstPage(this.getHtmlBuilder(), model, imageItem);
	}
	/**
	 * Function:显示上一页
	 * Create author:易贤建
	 * Create on:2008-4-15
	 */
	protected void prevPageItemAsImage(){
		ImageItem imageItem = new ImageItem();
		imageItem.setImage(getImagePath("arrowpageleft"));
		imageItem.setDisabledImage(getImagePath("arrowpageleft"));
		imageItem.setAlt(model.getMessages().getMessage("toolbar.tooltip.prevPage"));
		imageItem.setStyle("border:0");
		ToolbarItemUtils.buildPrevPage(this.getHtmlBuilder(), model,imageItem);
	}
	/*
	 * Function:显示上一页和下一页中间的点击页面后显示页码
	 * Create author:易贤建
	 * Create on:2008-4-15
	 */
	protected void forwardToPageWithPageNumber(){
		getHtmlBuilder().tabs(3).span().close();
		//如果是当前页，则不用超链接标签。如当前页为第2页，则渲染2时，不做处理
		int startIndex = getStartPageIndex(getModel().getLimit().getPage(),getTotalPages());
		int endIndex = getEndPageIndex(getModel().getLimit().getPage(),getTotalPages());
		for(int i = startIndex; i <= endIndex; i++){
			if(i == getModel().getLimit().getPage()){
				getHtmlBuilder().append(i).nbsp().newline();
			}else{
				renderPageNumberWithLink(i);
			}
		}
		getHtmlBuilder().tabs(3).spanEnd().newline();
	}

	/**
	 *
     * Function:下一页图片
     * Create author:易贤建
     * Create on:2008-4-15
	 */
	protected void nextPageItemAsImage(){
		ImageItem imageItem = new ImageItem();
		imageItem.setImage(getImagePath("arrowpageright"));
		imageItem.setDisabledImage(getImagePath("arrowpageright"));
		imageItem.setAlt(model.getMessages().getMessage("toolbar.tooltip.nextPage"));
		imageItem.setStyle("border:0");
		ToolbarItemUtils.buildNextPage(this.getHtmlBuilder(), model,imageItem);
	}

	/**
     * Function:最后一页图片
     * Create author:易贤建
     * Create on:2008-4-15
	 */
	protected void lastPageItemAsImage(){
		ImageItem imageItem = new ImageItem();
		imageItem.setImage(getImagePath("arrowpagerightend"));
		imageItem.setDisabledImage(getImagePath("arrowpagerightend"));
		imageItem.setAlt(model.getMessages().getMessage("toolbar.tooltip.lastPage"));
		imageItem.setStyle("border:0");
		ToolbarItemUtils.buildLastPage(this.getHtmlBuilder(), model,imageItem);
	}
	/**
     * Function:创建分页后面的文字消息：共**页
     * Create author:易贤建
     * Create on:2008-4-16
	 */
	protected void buildTotalPageMessage(){
		Integer totalPages = BuilderUtils.getTotalPages(model);
		String message = model.getMessages().getMessage("toolbar.text.totalPage", new String[]{totalPages.toString()});
		this.getHtmlBuilder().append(message);
	}

	/**
	 *
	     * Function:获取当前HtmlBuilder
	     * Create author:易贤建
	     * Create on:2008-4-28
	 */
	public HtmlBuilder getHtmlBuilder(){
		return this.htmlBuilder;
	}
	/**
	 *
	     * Function:
	     * Create author:易贤建
	     * Create on:2008-4-28
	 */
	public TableModel getModel(){
		return this.model;
	}
	/**
	 *
     * Function:获取table设置的imagePath属性值
     * Create author:易贤建
     * Create on:2008-4-28
	 */
	private String getImagePath(String imageName){
		String imagePath = model.getTableHandler().getTable().getImagePath();
		return imagePath.replaceFirst("\\*", imageName);
	}
	/**
     * Function:获取总页数
     * Create author:易贤建
     * Create on:2008-4-28
	 */
	private Integer getTotalPages(){
		Integer totalRows = getModel().getTableHandler().getTotalRows();
		Integer rowDisplay = getModel().getTableHandler().getTable().getRowsDisplayed();
		Integer tempRow = totalRows / rowDisplay;
		return totalRows%rowDisplay == 0? tempRow:tempRow + 1;
	}

	/**
     * Function:渲染页码：如当前页为2时，显示2这个数字，有超链接。如：
     * 如:<a href="javascript:setPageNumber('tableid','pagenumber');setFormAction('tableid','action');formSubmit('tableid')">currentPage</a>;
     * Create author:yixianjian
     * Create on:2008-4-28
	 */
	private void renderPageNumberWithLink(int currentPage){
		Table table = getModel().getTableHandler().getTable();
		StringBuffer strPageInfo =new StringBuffer().append("javascript:setPageNumber('").append(table.getTableId()).append("','");
		strPageInfo.append(currentPage).append("');").append("setFormAction('").append(table.getTableId()).append("'");
		strPageInfo.append(",'").append(table.getAction()).append("')");
		strPageInfo.append(";formSubmit('").append(table.getTableId()).append("');");

		getHtmlBuilder().a(strPageInfo.toString()).styleClass("tfoot").xclose().append("<u>").append(currentPage).append("</u>").aEnd().nbsp();
		getHtmlBuilder().newline();
	}
	/**
	 * 功能描述:  获取页码开始部分.如所有页码为10，当前页在6,那么该方法要求返回2<br>
	 * @return
	 * Create author:yixianjian <br>
	 * Create on:2008-9-12  <br>
	 */
	private int getStartPageIndex(int currentPage,int totalPages){
		//获取在10个分页情况下,左边需要显示多少个页码
		int leftPageTotal = allPages % 2 == 0 ? allPages / 2 -1 : allPages /2;
		//计算右边偏移量,当右边显示的页码数不够全部显示时  需要开始页码减去一个偏移量
		int rightTotal = allPages /2;
		int offset = currentPage + rightTotal > totalPages ? currentPage + rightTotal - totalPages : 0;

		return currentPage <= leftPageTotal  ? 1 : currentPage - leftPageTotal > offset  ? currentPage - leftPageTotal -  offset : 1;
	}
	/**
	 * 功能描述: 获取页码开始部分.如所有页码为10，当前页在4,那么该方法要求返回9<br>
	 * @param currentPage
	 * @param totalPages
	 * @return
	 * Create author:yixianjian <br>
	 * Create on:2008-9-12  <br>
	 */
	private int getEndPageIndex(int currentPage,int totalPages){
		//如果总页数小于配置的可显示的总页数时,显示全部页数
		if(totalPages < allPages)
			return totalPages;
		//计算左边偏移量  当当前页的左边没有4个页码(目前配置的最多显示10页,10页要求当前页左边显示4页,右边显示5页)时,需要右边多显示一些页码
		int leftPageTotal = allPages % 2 == 0 ? allPages / 2 -1 : allPages /2;
		int offset = currentPage <= leftPageTotal  ? leftPageTotal - currentPage + 1 : 0;

		int rightTotal = allPages /2;
		return currentPage + rightTotal <= totalPages ? currentPage + rightTotal + offset : totalPages;
	}
}
